package org.wutopia.labcloud.domain.gateway.filter;

import com.nimbusds.jwt.JWTClaimsSet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;
import org.wutopia.labcloud.library.common.utility.JwtUtility;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Component
@Slf4j
public class TokenAuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        return chain.filter(exchange);

//        // 1. 排除白名单路径（如登录接口）
//        String requestPath = exchange.getRequest().getURI().getPath();
//        if (requestPath.equals("/user/account/login")) {
//            return chain.filter(exchange);
//        }
//
//        // 2. 从 Header 提取 Token
//        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
//        if (token == null || !token.startsWith("Bearer ")) {
//            return unauthorized(exchange); // 返回 401
//        }
//        token = token.substring(7); // 去除 "Bearer "
//
//        // 3. 校验 Token 有效性
//        // 实现校验逻辑（见下文方案）
//        try {
//
//
//            JWTClaimsSet jwtClaimsSet = JwtUtility.verifyAndParseToken(token);
//            List<String> authorities = (List<String>)jwtClaimsSet.getClaim("authorities");
//
//            if(authorities.contains("leo")) {
//                return chain.filter(exchange);// 放行
//            }
//
//            for(String authority : authorities) {
//                PathPatternParser parser = new PathPatternParser();
//                PathPattern pattern = parser.parse(authority); // 解析模式
//                PathContainer path = PathContainer.parsePath(requestPath);
//
//                if(pattern.matches(path)) {
//                    return chain.filter(exchange);
//                }
//            }
//            log.info("没有匹配的权限：请求路径：{}， 权限：{}", requestPath, authorities);
//            return unauthorized(exchange);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//
//        return unauthorized(exchange); // 返回 401

    }


    private Mono<Void> unauthorized(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return -100; // 优先级
    }
}